package com.yuan.controller;

import com.qcloud.cos.model.ObjectMetadata;
import com.yuan.dataupload.ErWei;
import com.yuan.dataupload.Vehicle;
import com.yuan.dataupload.vo.DataLoadVo;
import com.yuan.service.VehicleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import static java.lang.System.out;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import java.io.File;

/*
 *  @author 雨安
 *  类名： DataController
 *  创建时间：2024/6/3
 */
//此控制器写入二维数据到vehicles表中
@RestController
@RequestMapping("/data/upload/api")
@CrossOrigin
public class DataController {

    //定义数据录入Service层
    @Resource
    private VehicleService vehicleService;

    //定义IR平台网络路径平台前缀
    private static final String ADMINIMG = "http://r.qj.cloudjoytech.com.cn/";

    @PostMapping(value = "/saveAll", produces = "application/json; charset=UTF-8")
    public String saveAllDataUpload(String doName, @RequestBody DataLoadVo dataLoadVo) throws IOException {
        out.println(dataLoadVo + "测试数据" + doName);
        //创建批量添加集合
        List<Vehicle> addList = new ArrayList<>();
        //拿到数据
        List<Vehicle> vehicleList = dataLoadVo.getData();
        //遍历数据
        for (Vehicle vehicle : vehicleList) {
            //判断当前遍历对象不为 null
            if (Objects.nonNull(vehicle)) {
                //拿到当前对象的图片数据
                List<ErWei> records = vehicle.getRecords();
                //遍历recoreds
                for (ErWei record : records) {
                    //判断操作对象不为 null
                    if (Objects.nonNull(record)) {
                        //判断是否有图片
                        if (StringUtils.isNotBlank(record.getImgUri())) { //录入了图片的情况
                            out.println(record + "执行添加的对象");
                            String img_str = uploadImgToAxd(record.getImgUri());
                            //创建添加到数据库的对象
                            Vehicle axdV = new Vehicle();
                            //设置车牌号
                            axdV.setCarNo(vehicle.getCarNo());
                            //设置下次维护时间
                            axdV.setNextMaintenanceTime(vehicle.getNextMaintenanceTime());
                            //设置公司名
                            axdV.setCoName(vehicle.getCoName());
                            //设置车辆类型
                            axdV.setVehicleType(vehicle.getVehicleType());
                            //设置维护时间
                            axdV.setImplementationDate(record.getImplementationDate());
                            //设置操作人
                            axdV.setDoName(doName);
                            //设置图片url
                            axdV.setImgUri(img_str);
                            //添加到集合中
                            addList.add(axdV);
                            //执行添加
//                            vehicleService.save(axdV);
                        } else {
                            //创建添加到数据库的对象
                            Vehicle axdV = new Vehicle();
                            //设置车牌号
                            axdV.setCarNo(vehicle.getCarNo());
                            //设置下次维护时间
                            axdV.setNextMaintenanceTime(vehicle.getNextMaintenanceTime());
                            //设置公司名
                            axdV.setCoName(vehicle.getCoName());
                            //设置车辆类型
                            axdV.setVehicleType(vehicle.getVehicleType());
                            //设置维护时间
                            axdV.setImplementationDate(vehicle.getImplementationDate());
                            //添加到集合中
                            addList.add(axdV);
                            //执行添加
//                            vehicleService.save(axdV);
                        }//无录入图片则 else

                    }//判断集合数据不为 null

                }//for each结束 图片集合数据

            }//判断非 null 结束

        }//for each 结束
        //执行批量添加
        Boolean saveBatch = vehicleService.saveBatch(addList);

        return saveBatch == true ? "录入成功" : "录入失败";
    }

    public String uploadImgToAxd(String imgUrl) throws IOException {
        // 替换为您的腾讯云账号的 SecretId 和 SecretKey
        String secretId = "AKIDzrX0EE0Vnwsd9RWNyKSLxKSLUO2SfdMq";
        String secretKey = "IBuSlrqiR1QipjPsENJ1WoshJhuufEYe";
        // 替换为您的腾讯云 COS 存储桶所在的地域
        String regionName = "ap-chongqing";
        // 替换为您的腾讯云 COS 存储桶名称
        String bucketName = "axd-1256474543";
        // 文件在 COS 中的路径和名称
        String key = imgUrl;
        // 远程文件的URL  net包 网络包 请求图片 java对象  java对象存入你那个里面
        String remoteFileUrl = ADMINIMG + imgUrl;
        if (remoteFileUrl != null) {
            try {
                BasicCOSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
                // 设置 COS 存储桶的地域
                Region region = new Region(regionName);
                // 创建 COS 客户端配置
                ClientConfig clientConfig = new ClientConfig(region);
                // 创建 COS 客户端
                COSClient cosClient = new COSClient(cred, clientConfig);
                // 创建上传请求
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, new URL(remoteFileUrl).openStream(), new ObjectMetadata());
                // 执行上传操作
                PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
                // 获取上传文件的访问URL
                String fileUrl = "https://" + bucketName + ".cos." + regionName + ".myqcloud.com/" + key;
                // 打印访问的 URL
                System.out.println("文件上传成功，访问URL：" + fileUrl);
                // 关闭 COS 客户端
                cosClient.shutdown();
                //返回Key存入数据库
                return key;
            } catch (Exception e) {
                e.printStackTrace();
                // 处理异常
            }
        } else {
            System.out.println("远程文件的URL为空，无法进行上传操作。");
            return "无";
        }
        return "无";
    }



}
